#define _CRT_SECURE_NO_WARNINGS
#include "List.h"
//void ListInit(LTNode** pphead)
//{
//	assert(pphead); 
//	*pphead = BuyLTNode(0);
//	(*pphead)->next = *pphead;
//	(*pphead)->prev = *pphead;
//}

void ListPrint(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{ 
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
LTNode* ListInit()
{
	
	LTNode *phead = BuyLTNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}
LTNode* BuyLTNode(LTDataType  x)
{
    LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	newnode->data = x;
	newnode->prev = NULL;
	newnode->next = NULL;

}


void ListPushBack(LTNode* phead, LTDataType x)
{
	/*assert(phead);
	LTNode* tail = phead->prev;
	LTNode* newnode = BuyLTNode(x);

	tail->next = newnode;
	newnode->prev = tail;

	newnode->next = phead;
	phead->prev = newnode;*/
	ListInsert(phead, x);
}


void ListPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	ListInsert(phead->next, x);
}



void ListPopBack(LTNode* phead)
{
	/*assert(phead);
	assert(phead->next != phead);
	LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;

	free(tail);
	tail = NULL;

	tailprev->next = phead;
	phead->prev = tailprev;*/
	ListErase(phead->prev);
}

void ListPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	ListErase(phead->next);
}

LTNode* ListFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data ==x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(LTNode * pos,LTDataType x)
{
	assert(pos);
	/*LTNode* newnode = BuyLTNode(x);
	pos->prev->next = pos;
	newnode->prev = pos->prev;

	pos->prev = newnode;
	newnode->next = pos;*/


	LTNode* newnode = BuyLTNode(x);
	LTNode* posPrev = pos->prev;
	newnode->next = pos;
	pos->prev = newnode;
	
	
	posPrev->next = newnode;
	newnode->prev = posPrev;

}



void ListErase(LTNode* pos)
{
	assert(pos);
	LTNode* Prev = pos->prev;
	LTNode* Next = pos->next;
	free(pos);
	pos = NULL;
	Prev->next = Next;
	Next->prev = Prev;

}

void ListDestory(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead;
	while (cur != phead)
	{
		LTNode* Next = cur->next;
		//ListErase(cur);
		free(cur);
		cur = Next;
	}
	free(phead);
	//phead = NULL;
}